package no.spk.util.inforama.analyze.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import no.spk.util.inforama.ArchiveEntryAnalyzer;
import no.spk.util.inforama.WebArchive;
import no.spk.util.inforama.analyze.ContainerAnalyzer;

public class ContainerAnalyzerImpl implements ContainerAnalyzer {

	public List<WebArchive> analyzeContainer(ServletContext servletContext) {
		ArchiveEntryAnalyzer aea = new ArchiveEntryAnalyzer();
		List<WebArchive> webArchives = getAllWebArchivesDeployedInContainer( servletContext );
		servletContext.log("webArchives found: " +webArchives.size());
		for (WebArchive webArchive : webArchives) {
			aea.analyzeWebArchive(webArchive);
		}
		return webArchives;
	}

	public List<WebArchive> getAllWebArchivesDeployedInContainer(ServletContext context) {
		context.log("Scanning container for web archives");
		List<WebArchive> webArchives = new ArrayList<WebArchive>();
		String path = context.getContextPath() + "//..//";

		path = ".//..//server//default//deploy";
		String tmp;
		File folder = new File(path);
		if (folder.isDirectory()) {
			File[] listOfFiles = folder.listFiles();

			for (int i = 0; i < listOfFiles.length; i++) {
				WebArchive archive = new WebArchive();
				if (listOfFiles[i].isFile()) {
					tmp = listOfFiles[i].getName();
					if (tmp.endsWith(".war") || tmp.endsWith(".WAR")) {
						archive.setArchivePath(new File(folder, tmp ));
						archive.setArchiveName(tmp);
						webArchives.add( archive );
					}
				}
			}
		}
		return webArchives;
	}
}
